<template>
    <div class="sys-dict-container">
        <a-row :gutter="8" style="width: 100%; height: 100%; flex: 1">
            <a-col :span="12" :xs="24" style="display: flex; height: 100%; flex: 1">
                <a-card title="字典" class="w-full">
                    <common-form
                        class="mb-2"
                        :model="state.queryForm"
                        name="menu-form"
                        @query="handleQuery"
                        @add="handleAdd"
                        @reset="handleReset"
                    >
                        <a-form-item
                                label="名称"
                                name="name"
                                class="w-1/2.5"
                            >
                            <a-input v-model:value="state.queryForm.name"/>
                        </a-form-item>
                    </common-form>
                    <a-table
                        :columns="columns"
                        :data-source="state.tableData"
                        :scroll="{ x: 1200 , y : 500}" 
                        :pagination="{
                            total: state.tableParams.total,
                            current: state.tableParams.page,
                            pageSize: state.tableParams.pageSize,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSizeOptions:['2','5','10','20'],
                            showTotal:(total:number) => `总数: ${total}`
                        }"
                        :loading="state.loading"
                        @change="changePagination"
                        :customRow="(record:ItemType)=>{
                            return {
                                onClick:()=>{
                                    handleRowClick(record)
                                }
                            }
                        }"
                    >
                        <template #bodyCell="{ column, text, record }">
                            <template v-if="column.dataIndex === 'sysFlag'">
                                <a-tag color="green" v-if="record.sysFlag == 1">是</a-tag>
                                <a-tag color="orange" v-else>否</a-tag>
                            </template>
                            <template v-if="column.dataIndex === 'isTenant'">
                                <a-tag color="green" v-if="record.isTenant == 1">是</a-tag>
                                <a-tag color="orange" v-else>否</a-tag>
                            </template>
                            <template v-if="column.dataIndex === 'status'">
                                <a-tag color="green" v-if="record.status == 1">启用</a-tag>
                                <a-tag color="orange" v-else>禁用</a-tag>
                            </template>
                            <template v-if="column.dataIndex ==='history'">
                                <div style="cursor: pointer;">
                                    <edit-record-history :row="record"/>
                                </div>
                            </template>
                            <template v-if="column.dataIndex === 'operation'">
                                <div class="w-full">
                                    <a-button 
                                        :icon="h(EditOutlined)" 
                                        ghost 
                                        type="primary" 
                                        class="mr-1"
                                        @click="handleEdit(record)" 
                                        :disabled="!hasPermission(record)"
                                    >
                                        编辑
                                    </a-button>
                                    <a-popconfirm
                                        title="确定删除?"
                                        @confirm="handleDelete(record)"
                                    >
                                        <a-button :icon="h(DeleteOutlined)" danger :disabled="record.sysFlag === 1 || !hasPermission(record)" >删除</a-button>
                                    </a-popconfirm>
                                </div>
                            </template>
                        </template>
                    </a-table>
                </a-card>
            </a-col>
            <a-col :span="12" :xs="24" style="display: flex; height: 100%; flex: 1">
                <a-card title="字典值" class="w-full">
                    <common-form
                        class="mb-2"
                        :model="state.queryDictDataParams"
                        name="menu-form"
                        @query="handleQuery2"
                        @add="handleAdd2"
                        @reset="handleReset2"
                    >
                        <a-form-item
                                label="显示文本"
                                name="label"
                                class="w-1/2.5"
                            >
                            <a-input v-model:value="state.queryDictDataParams.label"/>
                        </a-form-item>
                    </common-form>
                    <a-table
                        :columns="columns2"
                        :data-source="state.tableData2"
                        :scroll="{ x: 1200 , y : 500}" 
                        :pagination="{
                            total: state.tableDictDataParams.total,
                            current: state.tableDictDataParams.page,
                            pageSize: state.tableDictDataParams.pageSize,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSizeOptions:['2','5','10','20'],
                            showTotal:(total:number) => `总数: ${total}`
                        }"
                        :loading="state.loading2"
                        @change="changePagination2"
                    >
                        <template #bodyCell="{ column, text, record }">
                            <template v-if="column.dataIndex === 'extData'">
                                <a-tag color="orange" v-if="record.extData == null || record.extData == ''">空</a-tag>
                                <a-tag color="green" v-else>有值</a-tag>
                            </template>
                            <template v-if="column.dataIndex === 'status'">
                                <a-tag color="green" v-if="record.status == 1">启用</a-tag>
                                <a-tag color="orange" v-else>禁用</a-tag>
                            </template>
                            <template v-if="column.dataIndex ==='history'">
                                <div style="cursor: pointer;">
                                    <edit-record-history :row="record"/>
                                </div>
                            </template>
                            <template v-if="column.dataIndex === 'operation'">
                                <div class="w-full">
                                    <a-button 
                                        :icon="h(EditOutlined)" 
                                        ghost 
                                        type="primary" 
                                        class="mr-1"
                                        @click="handleEdit2(record)" 
                                    >
                                        编辑
                                    </a-button>
                                    <a-popconfirm
                                        title="确定删除?"
                                        @confirm="handleDelete2(record)"
                                    >
                                        <a-button :icon="h(DeleteOutlined)" danger :disabled="!hasPermission(state.selectDict)" >删除</a-button>
                                    </a-popconfirm>
                                </div>
                            </template>
                        </template>
                    </a-table>
                </a-card>
            </a-col>
        </a-row>
        <edit-dict-type ref="editDictTypeRef" @handle-query="handleQuery"/>
        <edit-dict-data ref="edtiDictDataRef" @handle-query="handleQuery2"/>
    </div>
</template>


<script setup lang="ts" name="sysDict">
import { reactive, onMounted, h ,ref} from 'vue';
import CommonForm from '@/components/common-form/index.vue'
import {apiSysDictDataDeletePost, apiSysDictDataPagePost, apiSysDictTypeDeletePost, apiSysDictTypePagePost} from '@/api/sys/sysDict'
import type { ResType } from '@/api/types';
import type { TableParamsResType } from '../onlineUser/type';
import type {ItemType, ItemType2} from './types'
import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
import editRecordHistory from '@/components/self/edit-record-history.vue';
import editDictType from './components/editDictType.vue';
import { useUserInfo } from '@/stores/userInfo';
import { AccountTypeEnum } from '@/enum';
import { showMsg } from '@/utils';
import editDictData from './components/editDictData.vue';

defineOptions({
    name: 'sysDict'
})

const userInfoStore = useUserInfo()

const edtiDictDataRef = ref<InstanceType<typeof editDictData>>()
const editDictTypeRef = ref<InstanceType<typeof editDictType>>()
const state = reactive({
    queryForm:{} as any,
    queryDictDataParams:{} as any,
    tableData:[] as any[],
    tableData2:[] as any[],
    loading:false,
    loading2:false,
    tableParams: {
		page: 1,
		pageSize: 50,
		total: 0 as any,
	},
    tableDictDataParams: {
		page: 1,
		pageSize: 50,
		total: 0 as any,
	},
    selectDict:{} as ItemType
})

const columns : any[] = [
    {
        title: '序号',
        align: "center",
        width: 60,
        customRender: ({ index }:{index:number}) => {
            return `${ index + 1 }`;
        },
        fixed: 'left',
    },
    {
        title: '字典名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        width: 150,
    },  
    {
        title: '字典编码',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
        width: 150,
    },    
    {
        title: '系统内置',
        dataIndex: 'sysFlag',
        key: 'sysFlag',
        align: 'center',
        width: 80,
    },    
    {
        title: '租户字典',
        dataIndex: 'isTenant',
        key: 'isTenant',
        align: 'center',
        width: 80,
    },  
    {
        title: '排序',
        dataIndex: 'orderNo',
        key: 'orderNo',
        align: 'center',
        width: 80,
    }, 
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center',
        width: 80,
    }, 
    {
        title: '修改记录',
        dataIndex: 'history',
        key: 'history',
        align: 'center',
        width: 150,
    }, 
    {
        title: '操作',
        align: 'center',
        key:"operation",
        dataIndex: 'operation',
        width: 200,
        fixed: 'right',
    }
]

const columns2 : any[] = [
    {
        title: '序号',
        align: "center",
        width: 60,
        customRender: ({ index }:{index:number}) => {
            return `${ index + 1 }`;
        },
        fixed: 'left',
    },
    {
        title: '显示文本',
        dataIndex: 'label',
        key: 'label',
        align: 'center',
        width: 150,
    }, 
    {
        title: '字典值',
        dataIndex: 'value',
        key: 'value',
        align: 'center',
        width: 100,
    }, 
    {
        title: '编码',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
        width: 100,
    },
    {
        title: '拓展数据',
        dataIndex: 'extData',
        key: 'extData',
        align: 'center',
        width: 100,
    },  
    {
        title: '排序',
        dataIndex: 'orderNo',
        key: 'orderNo',
        align: 'center',
        width: 80,
    }, 
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center',
        width: 80,
    }, 
    {
        title: '修改记录',
        dataIndex: 'history',
        key: 'history',
        align: 'center',
        width: 150,
    }, 
    {
        title: '操作',
        align: 'center',
        key:"operation",
        dataIndex: 'operation',
        width: 200,
        fixed: 'right',
    }
]
const handleQuery = async ()=>{
    state.loading = true
    const params = Object.assign({},state.queryForm,state.tableParams)
    const res = await apiSysDictTypePagePost(params) as ResType<TableParamsResType<ItemType>>
    state.tableData = res.data.result.items ?? []
    state.tableParams.total = res.data.result.total ?? 0
    state.loading = false
}

const handleAdd = async ()=>{
    editDictTypeRef.value?.handleOpen({sysFlag: 2, status: 1, orderNo: 100})
}

const handleReset = async ()=>{
    state.queryForm.name = ""
    handleQuery()
}

const changePagination = async(pagination:{current:number,pageSize:number})=>{
    state.tableParams.page = pagination.current
    state.tableParams.pageSize = pagination.pageSize
    await handleQuery()
}
const changePagination2 = async(pagination:{current:number,pageSize:number})=>{
    state.tableDictDataParams.page = pagination.current
    state.tableDictDataParams.pageSize = pagination.pageSize
    await handleQuery2()
}
const handleStausChange = async (record:ItemType)=>{
		
}

const handleEdit = async (record:ItemType)=>{
	editDictTypeRef.value?.handleOpen(record)
}

const handleDelete = async (record:ItemType)=>{
	await apiSysDictTypeDeletePost({id:record.id})
    showMsg("操作成功",'success')
    await handleQuery()
}

const hasPermission = (row:ItemType)=>{
    // enum结尾的无权限
	if (row.code?.toLowerCase().endsWith('enum')) return false;
    // 未设置内置参数的和是超管的有权限
	return row?.sysFlag === 2 || userInfoStore.state.userInfos.accountType === AccountTypeEnum.NUMBER_999;
}

const handleRowClick = async(record:ItemType)=>{
    state.selectDict = record
    state.queryDictDataParams.dictTypeId = record.id
    await handleQuery2()
}

const handleQuery2 = async ()=>{
	state.loading2 = true
	let params = Object.assign(state.queryDictDataParams, state.tableDictDataParams);
    const res =await apiSysDictDataPagePost(params) as ResType<TableParamsResType<ItemType2>>
    state.tableData2 = res.data.result.items ?? []
    state.tableDictDataParams.total = res.data.result.total ?? 0
    state.loading2 = false
}

const handleAdd2 = async ()=>{
	edtiDictDataRef.value?.handleOpen({status: 1, orderNo: 100, dictTypeId: state.queryDictDataParams.dictTypeId })
}
const handleEdit2 = async (record:ItemType)=>{
	edtiDictDataRef.value?.handleOpen(record)
}
const handleReset2 = async ()=>{
	state.queryDictDataParams.label = ""
	handleQuery2()
}

const handleDelete2 = async (record:ItemType)=>{
	await apiSysDictDataDeletePost({id:record.id})
    showMsg("操作成功",'success')
    await handleQuery2()
}
onMounted(()=>{
    handleQuery()
})  
</script>

<style lang="scss" scoped>
.ant-col{
    overflow: hidden!important;
}
:deep(.ant-btn >span) {
    display:inline-flex!important;
}
.sys-dict-container {}
</style>